package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决拦截的跨域请求问题
       if(!(handler instanceof HandlerMethod)){
           //如果请求不是动态请求,而是静态请求或者跨域预请求,直接放行
           return true;
       }
       //判断请求是否需要登录
        HandlerMethod method=(HandlerMethod) handler;
       if(!method.hasMethodAnnotation(RequireLogin.class)){
           return true;
       }
        //进行登录验证
        String token = request.getHeader("token");
        //根据key获取redis中的用户
        UserInfo user = userInfoRedisService.getUserInfoToToken(token);
        if(user==null){
            //设置响应数据类型
            response.setContentType("application/json; charset=utf-8");
            //返回一个JsonResult为登录提示,
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }
        return true;
    }
}
